﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Articles
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack )
            {
                FillData();
            }
        }

        private void FillData()
        {
            var sql = "select * from Articles";
            var dt = DbHelp.CRUD (sql);
            Giv.DataSource=dt ;
            Giv.DataBind();

           
        }

        protected void Giv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Giv.EditIndex = -1;
            FillData();
        }

        protected void Giv_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Giv.EditIndex = -1;
            FillData();
        }

        protected void Giv_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetCellValue(e.RowIndex, 1);
            var sql = string.Format("delete from users where id={0}", id);
            DbHelp.CRUD(sql);
            Giv .EditIndex = -1;
            FillData();
        }

        private object GetCellValue(int rowIndex, int v)
        {
            var cell = Giv .Rows[rowIndex ].Cells[v];
            var td = cell.Controls.Count > 0 ? ((TextBox)cell.Controls[0]).Text : cell.Text;
            return td;
        }

        protected void Giv_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var idString = GetCellValue(e.RowIndex, 1);
            var isOk = int.TryParse(idString , out int id);
            var uid = GetCellValue(e.RowIndex, 2);
            var pwd = GetCellValue(e.RowIndex, 3);
            var remarks = GetCellValue(e.RowIndex, 4);
            if (isOk)
            {
                var sql = string.Format("update Users set UsersName='{0}',UsersPwd='{1}',Ramrks='{2}'where Id='{3}'", uid, pwd, remarks, id);
                DbHelp .CRUD(sql);
            }
            else
            {
                var sql = string.Format("insert into Users (UsersName,UsersPwd,Ramrks)values('{0}','{1}','{2}')", uid, pwd, remarks);
                DbHelp .CRUD(sql);
            }

            Giv .EditIndex = -1;
            FillData();
        }


        protected void tj_Click(object sender, EventArgs e)
        {

            DataTable data = new DataTable();
            data.Columns.Add(new DataColumn("Id"));
            data.Columns.Add(new DataColumn("UsersName"));
            data.Columns.Add(new DataColumn("UsersPwd"));
            data.Columns.Add(new DataColumn("Ramrks"));
            foreach (GridViewRow row )
            {

            }

        }

 
    }
}